package wxpay.web.services;




import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.http.HttpServletRequest;
import org.apache.log4j.Logger;

import com.alibaba.druid.util.StringUtils;

import net.sf.json.JSONObject;
import util.Utils;
import wxpay.app.util.ConstantUtil;
import wxpay.app.util.Sign;
import wxpay.web.utils.CommonUtil;

/**
 * 小程序支付 调统一下单接口，返回
 * 
 * @author admin return{ payDataObj.put("appid", ConstantUtil.APP_ID);
 *         payDataObj.put("noncestr", noncestr); payDataObj.put("prepayid",
 *         prepay_id); payDataObj.put("timestamp", timestamp);
 *         payDataObj.put("signType", "MD5"); payDataObj.put("paySign",
 *         paySign); }
 *
 */
public class WeiXinPayGeyMap {
	Logger log = Logger.getLogger(WeiXinPayGeyMap.class);
	
	@SuppressWarnings("unchecked")
	public static JSONObject doWeixinPay(String price, String order_num, String openid,HttpServletRequest request) {
		HashMap<String, Object> resultHm = new HashMap<String, Object>();
		String totalStr = "0.0";
		totalStr = price;
		String nonce_str =PayCommonUtil.CreateNoncestr();
		StringBuffer formData = new StringBuffer();
		/**
		 * 统一下单接口
		 */
		SortedMap parameters = new TreeMap();
		parameters.put("appid", ConstantUtil.APP_ID);
		parameters.put("mch_id", ConstantUtil.PARTNER);
		parameters.put("nonce_str", nonce_str);
		parameters.put("body", "时光的朋友");
		parameters.put("out_trade_no", order_num);
		parameters.put("total_fee", totalStr);
		parameters.put("spbill_create_ip", IP4.getIpAddr(request));
		parameters.put("notify_url", Utils.getLoaclURL(request)
									+ ConstantUtil.NOYIFY_URL);
		parameters.put("openid", openid);
		parameters.put("trade_type", "JSAPI");
		String sign = Sign.createSign("UTF-8", parameters);
		parameters.put("sign", sign);
		String requestXML = PayCommonUtil.getRequestXml(parameters);
		String result = CommonUtil.httpsRequest(ConfigUtil.UNIFIED_ORDER_URL, "POST", requestXML);
		Map<String, String> map = new Hashtable<String, String>();
		try {
			map = XMLUtil.doXMLParse(result);
			System.out.println(map.toString());
		} catch (Exception e) {
			e.printStackTrace();
		}
		String noncestr = PayCommonUtil.CreateNoncestr();
		String timestamp = Long.toString((new Date().getTime()));
		String prepay_id = (String) map.get("prepay_id");
		/**
		 * 获取二次签名
		 */
		SortedMap params = new TreeMap();
		params.put("appId", ConstantUtil.APP_ID);
		params.put("nonceStr", noncestr);
		params.put("package", "prepay_id="+prepay_id);
		params.put("signType", "MD5");
		params.put("timeStamp", timestamp);// 时间支付穿
		String paySign =Sign.createSign("UTF-8", params);
		/**
		 *返回数据  主要事支付ID：prepay_id  和二次签名paySign
		 */
		JSONObject payDataObj = new JSONObject();
		payDataObj.put("appid", ConstantUtil.APP_ID);
		payDataObj.put("noncestr", noncestr);
		payDataObj.put("prepayid", prepay_id);
		payDataObj.put("timestamp", timestamp);
		payDataObj.put("signType", "MD5");
		payDataObj.put("paySign", paySign);
		payDataObj.put("total_fee", totalStr);
		return payDataObj;

	}
	  /** 
	    *  
	    * 方法用途: 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序），并且生成url参数串<br> 
	    * 实现步骤: <br> 
	    *  
	    * @param paraMap   要排序的Map对象 
	    * @param urlEncode   是否需要URLENCODE 
	    * @param keyToLower    是否需要将Key转换为全小写 
	    *            true:key转化成小写，false:不转化 
	    * @return 
	    */  
	   public static String formatUrlMap(Map<String, String> paraMap, boolean urlEncode, boolean keyToLower)  
	   {  
	       String buff = "";  
	       Map<String, String> tmpMap = paraMap;  
	       try  
	       {  
	           List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(tmpMap.entrySet());  
	           // 对所有传入参数按照字段名的 ASCII 码从小到大排序（字典序）  
	           Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>()  
	           {  
	  
	               @Override  
	               public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2)  
	               {  
	                   return (o1.getKey()).toString().compareTo(o2.getKey());  
	               }  
	           });  
	           // 构造URL 键值对的格式  
	           StringBuilder buf = new StringBuilder();  
	           for (Map.Entry<String, String> item : infoIds)  
	           {  
	               if (!StringUtils.isEmpty(item.getKey()))  
	               {  
	                   String key = item.getKey();  
	                   String val = item.getValue();  
	                   if (urlEncode)  
	                   {  
	                       val = URLEncoder.encode(val, "utf-8");  
	                   }  
	                   if (keyToLower)  
	                   {  
	                       buf.append(key.toLowerCase() + "=" + val);  
	                   } else  
	                   {  
	                       buf.append(key + "=" + val);  
	                   }  
	                   buf.append("&");  
	               }  
	  
	           }  
	           buff = buf.toString();  
	           if (buff.isEmpty() == false)  
	           {  
	               buff = buff.substring(0, buff.length() - 1);  
	           }  
	       } catch (Exception e)  
	       {  
	          return null;  
	       }  
	       return buff;  
	   }  
 
	
	
}
